<?php

namespace App\Http\Middleware\Admin;

use Closure;

class AdminAuthCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
    	$path = explode('/', request()->path());
    	$controller = ucfirst($path[0]) ?? 'Home';
    	$method = $path[1] ?? 'index';
    	
    	// 登录检测
    	if(!session('admin') && !preg_match('/^auth$/i', $controller)){
    		return redirect('/Auth/login');
    	}
    	
    	$admin = session('admin');
    	// 验证权限
    	$white_list = [
    			'/^Auth.*/i',
    			'/^Home.*/i',
    			'/^Profile.*/i',
    			'/^storage.*/i',
                        '/RegController.post/'
    	];
    	$target = $controller.'Controller.'.$method;
    	foreach($white_list as $v){
    		$white_flag = preg_match($v, $target);
    		if($white_flag){ break; }
    	}
    	if(!$white_flag){
    		$white_prefix = [
    				'/^ajax_.*/i'
    		];
    		foreach($white_prefix as $v){
    			$white_flag = preg_match($v, $method);
    			if($white_flag){ break; }
    		}
    	}
        
    	if(!$white_flag && !empty($controller) && !in_array($target, $admin['rights'])){
    		die(view('errors.error',['msg'=>'没有权限']));
    	}
        return $next($request);
    }
}
